package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.AddUserDTO;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.juli.logging.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * RestController:组合注解,相当于 ResponseBody注解 + Controller注解;
 * 1.加此注解后,类上无需再添加 Controller 注解;
 * 2.加此注解后,控制器方法上无需再添加 ResponseBody 注解.
 */
//@Controller
@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    //自动装配
    @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 1.添加用户功能
     */
    @ApiOperation(value = "添加用户功能")
    @PostMapping("insert")
    public JsonResult insert(AddUserDTO addUserDTO) {
        /*
            梳理业务逻辑：确定接口;
         */
        log.debug("addUserDTO = " + addUserDTO);
        User user = new User();
        //插入数据:一定使用实体类
        //复制属性:addUserDTO ---->  user
        BeanUtils.copyProperties(addUserDTO, user);

        //设置其他属性的值
        user.setCreated(new Date());
        //调用接口
        userMapper.insertUser(user);

        return JsonResult.ok();
    }

    /**
     * 2.用户列表功能
     */
    @ApiOperation(value = "用户列表功能")
    @GetMapping("userList")
    public JsonResult userList() {
        List<UserListVO>userList=userMapper.selectUserList();
        return JsonResult.ok(userList);
    }

    /**
     * 3.删除指定用户功能
     */
    @ApiOperation(value = "删除功能")
    @GetMapping("delete")
    public JsonResult delete(int id) {
        if (id<0){
            throw new IllegalArgumentException("ID值无效");

        }
        userMapper.deleteUser(id);

        return JsonResult.ok();
    }

    /**
     * 4.更新用户功能
     */
    @ApiOperation(value = "更新功能")
    @PostMapping("update")
    public JsonResult update(User user) {
        userMapper.updateUser(user);

        return  JsonResult.ok();
    }

    //5.查询指定用户功能
//    根据用户ID查询该用户的信息L全字段]
//    http://Localhost:8080/v1/users/用户ID值
    @ApiOperation(value = "查询功能")
    @GetMapping("{id}")
    public
    JsonResult selectById(@PathVariable int id) {
        log.debug("id = " + id);
        User user = userMapper.selectById(id);
        return JsonResult.ok(user);
    }


}









